﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace zijian666.ComponentModel.DataAnnotations;

/// <summary> 
/// 验证字符串不能包含脚本字符
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class NoScriptAttribute : ValidationAttribute
{
    private static readonly Regex HAS_SCRIPT = new("(<script)|(<[^>]+(?<on>on[a-z]*\\s*)?=['\"\\s]*(?(on)|([a-z]*)script\\s*:))", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    public NoScriptAttribute()
    {
        ErrorMessage = "字段 {0} 中包含非法的脚本内容";
    }

    public override bool IsValid(object value)
    {
        if (value is null)
        {
            return true;
        }
        if (value is not string str)
        {
            return true;
        }
        return HAS_SCRIPT.IsMatch(str) == false;
    }
}
